package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.modular.system.entity.QuartzTask;
import cn.stylefeng.guns.sys.modular.system.mapper.QuartzTaskMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.QuartzTaskParam;
import cn.stylefeng.guns.sys.modular.system.model.result.QuartzTaskResult;
import cn.stylefeng.guns.sys.modular.system.quartz.enums.JobStatusEnum;
import cn.stylefeng.guns.sys.modular.system.quartz.utils.QuartzManager;
import cn.stylefeng.guns.sys.modular.system.service.QuartzTaskService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

@Service
public class QuartzTaskServiceImpl extends ServiceImpl<QuartzTaskMapper, QuartzTask> implements QuartzTaskService {

    private static Logger logger = LoggerFactory.getLogger(QuartzTaskServiceImpl.class);

    @Resource
    QuartzManager quartzManager;


    @Override
    public void add(QuartzTaskParam param) {
        QuartzTask entity = getEntity(param);
        entity.setCreateUser(LoginContextHolder.getContext().getUserId());
        this.save(entity);
    }

    @Override
    public void delete(QuartzTaskParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(QuartzTaskParam param) {
        QuartzTask oldEntity = getOldEntity(param);
        QuartzTask newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        newEntity.setUpdateUser(LoginContextHolder.getContext().getUserId());
        this.updateById(newEntity);
    }

    @Override
    public QuartzTaskResult findBySpec(QuartzTaskParam param) {
        return null;
    }

    @Override
    public List<QuartzTaskResult> findListBySpec(QuartzTaskParam param) {
        return null;
    }

    private Serializable getKey(QuartzTaskParam param) {
        return param.getId();
    }


    private QuartzTask getEntity(QuartzTaskParam param) {
        QuartzTask entity = new QuartzTask();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }


    @Override
    public QuartzTask get(Long id) {
        return this.baseMapper.get(id);
    }

    @Override
    public LayuiPageInfo findPageBySpec(QuartzTaskParam query) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findPageBySpec(pageContext, query);
        return LayuiPageFactory.createPageInfo(page);

    }

    @Override
    public int update(QuartzTask task) {
        return this.baseMapper.update(task);
    }

    @Override
    public int remove(Long id) {
        try {
            QuartzTask task = get(id);
            quartzManager.deleteJob(task);
            return this.baseMapper.remove(id);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return 0;
        }

    }

    @Override
    public int removeBatch(Long[] ids) {
        for (Long id : ids) {
            try {
                QuartzTask task = get(id);
                quartzManager.deleteJob(task);
            } catch (SchedulerException e) {
                e.printStackTrace();
                return 0;
            }
        }
        return this.baseMapper.removeBatch(ids);
    }

    @Override
    public void initSchedule() throws SchedulerException {
        // 这里获取任务信息数据
        List<QuartzTask> jobList = this.baseMapper.list();
        for (QuartzTask task : jobList) {
            if (JobStatusEnum.RUNNING.getCode().equals(task.getJobStatus())) {
                quartzManager.addJob(task);
            }
        }
    }

    @Override
    public void changeStatus(Long jobId, String jobStatus) throws SchedulerException {
        QuartzTask task = get(jobId);
        if (task == null) {
            return;
        }
        if (JobStatusEnum.STOP.getCode().equals(jobStatus)) {
            quartzManager.deleteJob(task);
            task.setJobStatus(JobStatusEnum.STOP.getCode());
        } else {
            task.setJobStatus(JobStatusEnum.RUNNING.getCode());
            quartzManager.addJob(task);
        }
        update(task);
    }

    @Override
    public void updateCron(Long jobId) throws SchedulerException {
        QuartzTask task = get(jobId);
        if (task == null) {
            return;
        }
        if (JobStatusEnum.RUNNING.getCode().equals(task.getJobStatus())) {
            quartzManager.updateJobCron(task);
        }
        update(task);
    }

    @Override
    public void run(QuartzTask task) throws SchedulerException {
        quartzManager.runJobNow(task);
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private QuartzTask getOldEntity(QuartzTaskParam param) {
        return this.getById(getKey(param));
    }
}
